<?php

namespace app\model;

use app\service\System;
use app\stateData;
use think\Model;
use think\model\concern\SoftDelete;

class OrderTransactionRecord extends Model
{
    use SoftDelete;

    protected $createTime = 'create_date';
    protected $deleteTime = 'delete_date';


    public function getTransactionOrgAttr($name): array
    {
        return [
            'id' => $name,
            'text' => (new UserOrganization)->getStructureName($name) ?: ''
        ];
    }

    public function getTransactionUidAttr($name): array
    {
        return [
            'id' => $name,
            'text' => (new User)->getIdNickName($name) ?: ''
        ];
    }

    public function getExamineUidAttr($name): array
    {
        return [
            'id' => $name,
            'text' => (new User)->getIdNickName($name) ?: ''
        ];
    }

    public function getSettlementMethodAttr($name): array
    {
        return [
            'id' => $name,
            'text' => stateData::$_jsfs[$name]
        ];
    }

    public function getTypeAttr($name): array
    {
        return [
            'id' => $name,
            'text' => stateData::$_js_type[$name]
        ];
    }

    public function getStatusAttr($name): array
    {
        return [
            'id' => $name,
            'text' => stateData::$_js_status[$name]
        ];
    }

    public function getAnnexAttr($name)
    {
        if (empty($name)) return '';
        $name = explode(',',$name);
        foreach($name as &$value){
            $value = config('file.url').$value;
        }
        $name = implode(',',$name);
        return $name;
//        return str_replace('\\', '/', 'http://' . $_SERVER['HTTP_HOST'] . '/storage/' . $name);
    }
    public function getAnnexNameAttr($name)
    {
        if (empty($name)) return '';
        return $name;
    }

    public function getNotesAttr($name)
    {
        if (empty($name)) return '';
        return $name;
    }

    public function addDataModel($data)
    {
        return self::create($data);
    }

    public function addAllDataModel($data)
    {
        return $this->saveAll($data);
    }

    public function getTransactionDateAttr($name)
    {
        if (empty($name) || $name == '0000-00-00 00:00:00'){
            return "";
        }
        return $name;
    }
    public function getSubmitDateAttr($name)
    {
        if (empty($name) || $name == '0000-00-00 00:00:00'){
            return "";
        }
        return $name;
    }
    public function getShUidAttr($name)
    {
        if (empty($name)){
            return [
                'id'=>'',
                'text'=>''
            ];
        }
        return [
            'id' => $name,
            'text' => (new User)->getIdNickName($name) ?: ''
        ];
    }

    public function editDataModel($id, $data)
    {
        return $this->where('id',$id)->update($data);
    }

    /**
     * 通过id查询收付款
     * @param $id
     * @return array|null
     */
    public function getIdDataModel($id): ?array
    {
        $data = $this->where(['id' => $id])->findOrEmpty();
        if (!$data->isEmpty()) {
            return $data->toArray();
        }
        return null;
    }

    /**
     * 通过收付款编号查询收付款合集
     * @param $transactionCode
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTransactionCodeDataModel($transactionCode, $type): array
    {
        return $this->where(['transaction_code' => $transactionCode, 'transaction_type' => $type])->select()->toArray();
    }

    /**
     * 根据延伸补充库id 收付款类型查询
     * @param $oid
     * @param $type 1收款  2付款
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderDealIdDataModel($oid, $cer): array
    {
        return $this->where(['order_company_id' => $oid, 'certificate_code' => $cer])->select()->toArray();
    }

    /**
     * //订单详情中显示所有的数据
     * 根据延伸补充库id 收付款类型查询审批通过的数据
     * @param $oid
     * @param $type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderTransactionStatus($oid, $cer, $type)
    {
//        return $this->where(['order_company_id' => $oid, 'transaction_type' => $type, 'status' => 1, 'certificate_code' => $cer])->whereOr(['status'=>2])->select()->toArray();
        return $this->where(['order_company_id' => $oid, 'transaction_type' => $type, 'certificate_code' => $cer])->select()->toArray();
    }

    /**
     * 收付款详情中只显示通过的数据
     * @param $oid
     * @param $cer
     * @param $type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPassOrderTransactionStatus($oid, $cer, $type)
    {
        return $this->where(['order_company_id' => $oid, 'transaction_type' => $type, 'status' => 1, 'certificate_code' => $cer])->select()->toArray();
    }



    /**
     * 根据证书编码查询收付款信息
     * @param $cer
     * @param $type 1收款  2付款
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCerDataModel($cer, $type): array
    {
        return $this->where(['certificate_code' => $cer, 'transaction_type' => $type])->select()->toArray();
    }

    /**
     * 根据证书编码查询 审核通过的收付款信息
     * @param $cer
     * @param $type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCerStatusDataModel($cer, $type): array
    {
        $userModel = new User();
        $systemService = new System();
        $orgModel = new UserOrganization();
        $userService = new \app\service\User();
        $data = $this->where(['certificate_code' => $cer, 'transaction_type' => $type])->select()->toArray();
//        $data = $this->whereRaw ('(certificate_code = "'.$cer.'" AND transaction_type ='.$type.' and status =1) OR (certificate_code ="'.$cer.'" AND transaction_type ='.$type.' and status =2)')->select()->toArray();
        //增加提交人部门
        foreach ($data as &$datum) {
            if ($datum['transaction_uid']['id']){
                $orgId = $userModel->getUidOrgId($datum['transaction_uid']['id']);
                $datum['transaction_org']['id'] = strrev(rtrim ($systemService->getParentIdStr($orgId,$orgModel->getStructure ()),','));
                $datum['transaction_org']['text'] = $userService->getUidOrgTitle($datum['transaction_uid']['id']);
            }
        }
        return $data;
    }

    /**
     * 查询收付款列表
     * @param $type
     * @return \app\model\OrderTransactionRecord[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTransactionListModel($type, $uidArr, $uid, $page, $pageNum)
    {
//        $data = $this
////            ->whereIn ('transaction_uid',$uidArr)
////                ->fetchSql(true)
//            ->whereRaw('examine_uid ='.$uid.' AND transaction_type ='.$type .' OR sh_uid='.$uid.' AND transaction_type ='.$type)
////            ->whereOr (['examine_uid'=>$uid,'transaction_type' => $type])
////            ->whereOr (['sh_uid'=>$uid,'transaction_type' => $type])
//
////            ->page ($page,$pageNum)
//            ->order('create_date DESC')
//            ->group('transaction_code')
//            ->select()->toArray();
//        return $data;
        return $this->whereRaw('examine_uid ='.$uid.' AND transaction_type ='.$type .' OR sh_uid='.$uid.' AND transaction_type ='.$type)
            ->order('create_date DESC')
            ->group('transaction_code')
            ->column ('id');
    }

    public function getTransactionIdListModel($id)
    {
        return $this->whereRaw('id ='.$id)->select()->toArray();
    }

    public function getTransactionCountModel($type, $uidArr, $uid)
    {
        return $this
//            ->whereIn ('transaction_uid',$uidArr)
//            ->whereOr (['examine_uid'=>$uid])
            ->whereRaw('examine_uid ='.$uid.' AND transaction_type ='.$type .' OR sh_uid='.$uid.' AND transaction_type ='.$type)
//            ->group('transaction_code')
            ->count();
    }

    /**
     * 通过收付款
     * @param $id
     * @return \app\model\OrderTransactionRecord
     */
    public function passOpModel($id,$refuse_text)
    {
        return $this->where(['id' => $id])->update(['status' => 1,'refuse_text'=>$refuse_text]);
    }

    /**
     * 拒绝收付款
     * @param $id
     * @return \app\model\OrderTransactionRecord
     */
    public function refuseOpModel($id, $refuse_text)
    {
        return $this->where(['id' => $id])->update(['status' => 2, 'refuse_text' => $refuse_text,'sh_uid'=>'']);
    }

    /**
     * 查询单条信息
     * @param $id
     * @return array|null
     */
    public function getIdFindModel($id)
    {
        $data = $this->where(['id' => $id])->findOrEmpty();
        if (!$data->isEmpty ()){
            return $data->toArray ();
        }
        return null;
    }

    public function delTransactionModel($id): bool
    {
        return self::destroy($id);
    }

    public function editTransactionModel($data)
    {
        return self::update($data);
    }

    /**
     * 查询id范围 type数据
     * @param $idArr
     * @param $type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTypeDataModel($idArr, $type): array
    {
        return $this->where(['transaction_type' => $type])->whereIn('id', $idArr)->order('id desc')->column ('id');
    }

    /**
     * 查询有关所有收付款
     * @param $type
     * @param $cer
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCertificateCodeDataTypeModel($type, $cer)
    {
        return $this->where(['certificate_code' => $cer, 'type' => $type])->select()->toArray();
    }

    /**
     * 查询收付款单号有关所有收付款
     * @param $transaction
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTransactionCodeCodeDataModel($transaction)
    {
        return $this->where(['transaction_code' => $transaction])->select()->toArray();
    }

    /**
     * 查询是否有多条收付款
     * @param $transaction
     * @return int
     * @throws \think\db\exception\DbException
     */
    public function getTransactionCodeIsDtDataModel($transaction)
    {
        return $this->where(['transaction_code' => $transaction])->count ();

    }
    /**
     * 查询证书编号已经完成的收款
     * @param $cer
     * @param int $status //1审核通过的
     * @param int $transaction_type //1已收  2已付
     * @return array|null
     */
    public function getOrderStatusYsModel($cer, int $status = 1, int $transaction_type = 1): ?array
    {
        $data = $this->where(['certificate_code' => $cer, 'status' => $status, 'transaction_type' => $transaction_type])->field('sum(price) as all_price')->findOrEmpty();
        if (!$data->isEmpty()) {
            return $data->toArray();
        }
        return null;
    }

    /**
     * 查询时间段内所有已收已付
     * @param $uidArr
     * @param $startDate
     * @param $endDate
     * @param $transaction_type
     * @param $status
     * @return array
     */
    public function getAllOrderStatusYsModel( $fUidArr,$examineArr,$startDate,$endDate, $transaction_type = 1,$status = 1): ?array
    {
        $orderLogModel = new OrderTransactionLog();
        if ($transaction_type == 1){
            $text = '收款审核通过';
        }else{
            $text = '付款审核通过';
        }

        if (is_array ($fUidArr)){
            $fUidArr = implode ($fUidArr,',');
        }
        $whereIn = '';
        if ($fUidArr && $examineArr){
            $whereIn = 'transaction_uid in ('.$fUidArr.' ) and (examine_uid in ('.$examineArr.') OR sh_uid in ('.$examineArr.'))';
        }else if ($fUidArr){
            $whereIn = 'transaction_uid in ('.$fUidArr.')';
        }else if ($examineArr){
            $whereIn = 'examine_uid in ('.$examineArr.') OR sh_uid in ('.$examineArr.')';
        }

        $data = $this->where([ 'status' => $status, 'transaction_type' => $transaction_type])
            ->whereRaw ($whereIn)
            ->whereBetweenTime ('transaction_date',$startDate,$endDate)
            ->column('price,id');

        $all_price = 0;
        foreach ($data as $datum) {
            $data_create_date = $orderLogModel->getTypeExamineDateModel($datum['id'],$text);

            if (strtotime ($data_create_date) >= strtotime ($startDate) && strtotime ($data_create_date) <= strtotime ($endDate)){
                $all_price += $datum['price'];
            }
        }

        return ['all_price'=>$all_price];
    }

    /**
     * 获取id证书编号对应的已收已付
     * @param $id
     * @param $cer
     * @param int $status
     * @param int $transaction_type
     * @return array|null|string
     */
    public function getOrderStatusIdYsModel($id,$cer, int $status = 1, int $transaction_type = 1): ?array
    {
        $data = $this->where(['certificate_code' => $cer, 'status' => $status, 'transaction_type' => $transaction_type,'order_company_id'=>$id])
            ->field('sum(price) as all_price')->findOrEmpty();
        if (!$data->isEmpty()) {
            return $data->toArray();
        }
        return '';
    }

    public function getOrderStatusIdDateYsModel($tid,$create_date,$id,$cer, int $status = 1, int $transaction_type = 1)
    {
        $orderLogModel = new OrderTransactionLog();
        if ($transaction_type == 1){
            $text = '收款审核通过';
        }else{
            $text = '付款审核通过';
        }
//        $data = $this->where(['certificate_code' => $cer, 'status' => $status, 'transaction_type' => $transaction_type,'order_company_id'=>$id])
//            ->whereTime('create_date', '<', $create_date)
//            ->field('sum(price) as all_price')->findOrEmpty();
//        if (!$data->isEmpty()) {
//            return $data->toArray();
//        }
//        return '';
        $all_price = 0;
        $data = $this->where(['certificate_code' => $cer, 'status' => $status, 'transaction_type' => $transaction_type,'order_company_id'=>$id])
//            ->whereTime('create_date', '<', $create_date)
                ->field('price,id')
            ->select ()->toArray ();

        //获取本条收付款通过时间
        $create_dates = $orderLogModel->getTypeExamineDateModel($tid,$text);

        //查询通过审核时间
        foreach ($data as $datum) {
            if (!$create_dates){
                $all_price += $datum['price'];
                continue;
            }
            $data_create_date = $orderLogModel->getTypeExamineDateModel($datum['id'],$text);

            if (strtotime ($data_create_date) < strtotime ($create_dates)){
                $all_price += $datum['price'];
            }
        }
//print_r ($all_price);
//        echo  PHP_EOL;
        return ['all_price'=>$all_price];

    }


    public function getOrderStatusModel($cer)
    {
        $data = $this->where(['transaction_code' => $cer])->field('sum(price) as all_price')->findOrEmpty();
        if (!$data->isEmpty()) {
            return $data->toArray();
        }
        return null;
    }

    /**
     * 获取收付款编号所有收付款
     * @param $transactionCode
     * @return mixed
     */
    public function getTransactionCodeSumModel($transactionCode)
    {
        return $this->where(['transaction_code' => $transactionCode])->field('sum(price) as sum_get_price')->find();
    }

    /**
     * 通过证书编号id查询收付款最新时间
     * @param $cer
     * @param $id
     * @param $type
     * @return mixed
     */
    public function getFindDataModel($cer, $id, $type)
    {
        return $this->where(['order_company_id' => $id, 'certificate_code' => $cer, 'transaction_type' => $type,'status'=>1])->order('transaction_date DESC')->value('transaction_date');
    }

    /**
     * 获取证书编号id收付款合计
     * @param $cer
     * @param $id
     * @param $type
     * @return \app\model\OrderTransactionRecord|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCerTypeAllPriceModel($cer, $id, $type)
    {
        return $this->where(['order_company_id' => $id, 'certificate_code' => $cer, 'transaction_type' => $type,'status'=>1])->field('sum(price) as all_price')->find();
    }
    public function getInfo($id)
    {
        return $this->where('id', $id)->find();
    }

    /**
     * 通过id查询文件名称
     * @return mixed
     */
    public function getValueAnnexNameModel($id)
    {
        return $this->where (['id'=>$id])->value ('annex_name');
    }

    /**
     * 通过收付款编号查询收付款对应的多条其中一条id
     * @param $code
     * @return mixed
     */
    public function getIdModel($code)
    {
        return $this->where (['transaction_code'=>$code])->value ('id');
    }

    /**
     * 批量查询id数据
     * @param $didArr
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getIdArrDataModel($didArr)
    {
        return $this->whereIn ('id',$didArr)->select ()->toArray ();
    }

    public function getIdDataSModel($transaction_code)
    {
        return $this->where (['transaction_code'=>$transaction_code])->column('id');
    }

    /**
     * 报表中心-流水
     * @param $type
     * @param $startDate
     * @param $endDate
     * @param $fUidArr//发起人
     * @param $examineArr//审核人
     * @param $status
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTypeStatusAllDataModel($type,$startDate,$endDate,$fUidArr,$examineArr,$status=1)
    {
        if (is_array ($fUidArr)){
            $fUidArr = implode ($fUidArr,',');
        }
        $whereIn = '';
        if ($fUidArr && $examineArr){
            if ($type == 2){
                $whereIn = 'transaction_uid in ('.$fUidArr.' ) and sh_uid in ('.$examineArr.'))';
            }else{
                $whereIn = 'transaction_uid in ('.$fUidArr.' ) and examine_uid in ('.$examineArr.')';
            }
        }else if ($fUidArr){
            $whereIn = 'transaction_uid in ('.$fUidArr.')';
        }else if ($examineArr){
            if ($type == 2){
                $whereIn = 'sh_uid in ('.$examineArr.')';
            }else{
                $whereIn = 'examine_uid in ('.$examineArr.')';
            }
        }

        return $this->where (['status'=>$status,'transaction_type'=>$type])
            ->whereRaw($whereIn)
            ->column ('id');
//        return $this->where (['status'=>$status,'transaction_type'=>$type])
//            ->whereRaw($whereIn)
//            ->select ()->toArray ();

    }

    /**
     * 查询今日订单个数
     * @param $type
     * @return int
     * @throws \think\db\exception\DbException
     */
    public function getToDayCountFindModel($type):int
    {
        return  $this->where (['transaction_type'=>$type])->whereDay('create_date')->count ();
    }


}